package com.example.blog_springboot.service;

import com.example.blog_springboot.config.ErrorException;
import com.example.blog_springboot.config.RepeatException;
import com.example.blog_springboot.mapper.BlogMapper;
import com.example.blog_springboot.mapper.UserMapper;
import com.example.blog_springboot.model.Blog;
import com.example.blog_springboot.model.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BlogMapper blogMapper;

    public void login(String username, String password, HttpServletRequest request) throws Exception {
        User user = userMapper.selectByUsername(username);
        if(user==null||user.equals("")){
            throw new ErrorException();
        }
        if (!user.getPassword().equals(password)) {
            throw new ErrorException();
        }
        HttpSession session = request.getSession(true);
        if (session == null) {
            throw new Exception();
        }
        session.setAttribute("user", user);
    }

    public User getWriter(String blogId,User user) {
        Blog blog = blogMapper.selectOne(blogId);
        User writer = userMapper.selectByUserId(blog.getUserId());
        if(writer.getUserId()==user.getUserId()){
            writer.setYourBlog(true);
        }
        return writer;
    }

    public void add(String username, String password) throws RepeatException {
        User user = userMapper.selectByUsername(username);
        if(!(user==null||user.equals(""))){
            throw new RepeatException();
        }
        userMapper.add(username,password);
    }

    public void logout(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession(false);
        if (session == null) {
            throw new Exception();
        }
        session.removeAttribute("user");
    }
}
